var actions = new Array();
actions["1000"] = "Access granted";

actions["2010"] = "Register data object";
actions["2011"] = "Register data replica";
actions["2012"] = "Unregister data object";

actions["2020"] = "Register delayed rule";
actions["2021"] = "Modify delayed rule";
actions["2022"] = "Delete delayed rule";

actions["2030"] = "Register resource";
actions["2031"] = "Delete resource";

actions["2040"] = "Delete user";

actions["2050"] = "Register collection (requested by admin)";
actions["2051"] = "Register collection";

actions["2060"] = "Delete collection (requested by admin)";
actions["2061"] = "Delete collection";
actions["2062"] = "Delete zone";

actions["2064"] = "Register zone";

actions["2070"] = "Modify user name";
actions["2071"] = "Modify user type";
actions["2072"] = "Modify user zone";
actions["2073"] = "Modify user DN";
actions["2074"] = "Modify user informations";
actions["2075"] = "Modify user comment";
actions["2076"] = "Modify user password";

actions["2080"] = "Modify group";
actions["2090"] = "Modify resource";
actions["2091"] = "Modify resource free space";
actions["2092"] = "Modify resource group";
actions["2093"] = "Modify zone";

actions["2100"] = "Register user";
actions["2110"] = "Add AVU metadata";
actions["2111"] = "Delete AVU metadata";
actions["2112"] = "Copy AVU metadata";

actions["2120"] = "Modify access control on object";
actions["2121"] = "Modify access control on collection";
actions["2122"] = "Recursively modify access control on collection";

actions["2130"] = "Rename data object";
actions["2131"] = "Rename collection";

actions["2140"] = "Move data object";
actions["2141"] = "Move collection";

actions["2150"] = "Register token";
actions["2151"] = "Delete token";


function initPlugins() {
  $(document).ready(function() {
  	$("#autocompleteLoading").html("<img src='images/loading.gif'>&nbsp;&nbsp;Initializing autocompletion...");
  	
    $.get("irods.xml?_uri=//com.enginframe.irods/get_irods_users_list", function(data) {
      var serviceData = data.substring((data.indexOf("##START##") + 9), data.indexOf("##END##"));
      var irodsUsers = serviceData.split("|");
      $("#irodsUser").autocomplete(irodsUsers).focus();
      
      var queryString = window.location.search.substring(1);
      var queryParameters = queryString.split("&");
      if (queryParameters.length == 2) {
      	var tokens = queryParameters[1].split("=");
      	if (tokens.length == 2) {
      		$("#irodsUser").val(tokens[1]);
      		getAuditTrails("admin");
      	}
      }
      
      $("#autocompleteLoading").html("");
    }, "text");
    
    $("#startDate").datepicker();
    $("#endDate").datepicker();
  });
}

function toggleUserDetails() {
  if ($("#userInfoDetails").is(":visible")) {
    $("#toggleButton").val("Show user details");
  } else {
    $("#toggleButton").val("Hide user details");
  }
  $("#userInfoDetails").toggle(500);
}

function getAuditTrails(role) {
  var irodsUser;
  if (role == "admin") {
    irodsUser = $("#irodsUser").val();
  } else {
    irodsUser = $("#irodsUser").html();
  }
  if (irodsUser.length == 0) {
    alert("Please specify an iRODS user name.");
    return;
  }

  $("#userInfo").html("<img src='images/loading.gif'>&nbsp;&nbsp;Fetching data from iRODS, please wait...");
  $("#auditResult").html("<img src='images/loading.gif'>&nbsp;&nbsp;Fetching data from iRODS, please wait...");
  
  $.get("irods.xml?_uri=//com.enginframe.irods/get_irods_user_info&_irods_username=" + irodsUser, function(data) {
    var userInfo = data.substring((data.indexOf("##START##") + 9), data.indexOf("##END##"));
    var output = "";
    
    if (userInfo.length != 0) {
      var tokens = userInfo.split("|");

      output += "<table cellpadding='0' cellspacing='0'><tr>"
      output += "<td class='ontop'><input id='toggleButton' type='button' value='Show user details' onclick='toggleUserDetails()'></td>"
      output += "<td><table id='userInfoDetails' cellpadding='2' cellspacing='2'>";
      output += "<tr><td class='uid-label'>User ID:</td><td>" + tokens[1] + "</td></tr>";
      output += "<tr><td class='uid-label'>Type:</td><td>" + tokens[2] + "</td></tr>";
      output += "<tr><td class='uid-label'>Informations:</td><td><pre class='normal-font'>" + tokens[5] + "</pre></td></tr>";
      output += "<tr><td class='uid-label'>Comment:</td><td><pre class='normal-font'>" + tokens[6] + "</pre></td></tr>";
      output += "<tr><td class='uid-label'>Create time:</td><td>" + tokens[7] + "</td></tr>";
      output += "<tr><td class='uid-label'>Modify time:</td><td>" + tokens[8] + "</td></tr>";
      output += "</table></td></table><p/>";
    }

    $("#userInfo").html(output);
  });

  $.get("irods.xml?_uri=//com.enginframe.irods/get_irods_audit_by_username&_irods_username=" + irodsUser + "&_start_date=" + $("#startDate").val() + "&_end_date=" + $("#endDate").val(), function(data) {

    var auditData = data.substring((data.indexOf("##START##") + 9), data.indexOf("##END##"));
    var items = auditData.split("\n");
    var infos = items[0].split("|");
    var output = "<div>Audit data for user <b>" + infos[0] + "</b> from <b>" + infos[1] + "</b> to <b>" + infos[2] + "</b>:</div><p/>";

    output += "<div><table id='auditData' class='list-table' cellpadding='5' cellspacing='0'><thead>";
    output += "<tr class='lt-header'>";
    output += "<th style='display: none' />";
    output += "<th class='lt-header-field'>Type</th>";
    output += "<th class='lt-header-field'>Name</th>";
    output += "<th class='lt-header-field'>Action</th>";
    output += "<th class='lt-header-field'>Comment</th>";
    output += "<th class='lt-header-field'>Date</th></tr></thead><tbody>";

    for (var i = 1; i < (items.length); i++) {
      var tokens = items[i].split("|");
      
      if (tokens.length > 1) {
        output += "<tr id='ad-row-" + i + "' class='lt-row' title='Click to show/hide metadata and ACL' style='cursor: pointer' onclick='toggleMetadataRow(" + i + ")'>";
        output += "<td id='ad-id-" + i + "' style='display: none'>" + tokens[0] + "</td>";
        output += "<td id='ad-type-" + i + "'>" + tokens[4] + "</td>";
        output += "<td><pre id='ad-object-" + i + "' class='normal-font'>" + tokens[5] + "</pre></td>";
        output += "<td>" + actions[tokens[1]] + "</td>";
        output += "<td><pre class='normal-font'>" + tokens[2] + "</pre></td>";
        output += "<td>" + tokens[3] + "</td></tr>";
      }
    }

    output += "</tbody></table></div>";
    $("#auditResult").html(output);
    
    $("#auditData").dataTable({
      "bAutoWidth": false,
      "bSortClasses": false,
      "aoColumns": [
          {"bSearchable": false, "bSortable": false},
          null,
          null,
          null,
          null,
          null
      ],
      oLanguage: { "sSearch": "Filter:" }
    });
  });
}

function toggleMetadataRow(i) {
  function Index() {};
  Index.prototype.value = i;

  if ($("#ad-metadata-row-" + i).length == 0) {
    $("#ad-row-" + i).after("<tr id='ad-metadata-row-" + i + "' class='lt-metadata-row' title='Click to show/hide metadata and ACL' onclick='toggleMetadataRow(" + i + ")'><td class='lt-metadata-field' colspan='5'><table style='width: 100%'><tr><td id='metadata-content-" + i + "' /><td id='acl-content-" + i + "' /></tr></table></td></tr>");
    $("#ad-metadata-row-" + i).attr("style", "background-color: " + $("#ad-row-" + i).css("backgroundColor"));
  }

  if ($("#metadata-content-" + i).html().length == 0) {
    $("#metadata-content-" + i).html("<img src='images/loading.gif'>&nbsp;&nbsp;Fetching metadata from iRODS, please wait...");
    $("#acl-content-" + i).html("<img src='images/loading.gif'>&nbsp;&nbsp;Fetching ACL from iRODS, please wait...");

    var typeParam = "-d"
    var objParam = "DATA_ID";
    var typeValue = $("#ad-type-" + i).html();
    if (typeValue == "Collection") {
      typeParam = "-C";
      objParam = "COLL_ID";
    } else if (typeValue == "User") {
      typeParam = "-u";
      objParam = "USER_ID";
    }

    $.get("irods.xml?_uri=//com.enginframe.irods/get_irods_metadata&_irods_object=" + $("#ad-object-" + i).html() + "&_type_param=" + typeParam, function(data) {
      var metadataList = data.substring((data.indexOf("##START##") + 9), data.indexOf("##END##"));
      var output;
      
      if (metadataList.length == 0) {
         output = "No metadata for this object."
      } else {
        var metadata = metadataList.split("\n");
        output = "<pre>"

        for (var i = 0; i < metadata.length; i++) {
          var tokens = metadata[i].split("|");
          output += tokens[0] + ": " + tokens[1] + " " + tokens[2] + "\n";
        }

        output += "</pre>";
      }

      $("#metadata-content-" + new Index().value).html(output);
    });
    
    $.get("irods.xml?_uri=//com.enginframe.irods/get_irods_acl&_irods_object_id=" + $("#ad-id-" + i).html() + "&_object_query_name=" + objParam, function(data) {
    	var aclList = data.substring((data.indexOf("##START##") + 9), data.indexOf("##END##"));
    	var output;
    	
    	if (aclList.length == 0) {
    		output = "No ACL informations for this object."
    	} else {
	    	output = "<table class='acl-table'><tr class='at-header'>";
	    	output += "<th class='at-header-field'>User name</th>";
	    	output += "<th class='at-header-field'>Access action</th></tr>";
	    	
	    	var aclItems = aclList.split("\n");
	    	for (var i = 0; i < aclItems.length; i++) {
	    		var tokens = aclItems[i].split("|");
	    		if (tokens.length > 1) {
	    			output += "<tr><td>" + tokens[0] + "</td><td>" + tokens[1] + "</td>";
	    		}
	    	}
	    	
	    	output += "</table>";
    	}
    	
    	$("#acl-content-" + new Index().value).html(output);
    });
  }

  $("#ad-metadata-row-" + i).toggle();
}

function initRulesList(role) {
	$("#rulesLoading").html("<img src='images/loading.gif'>&nbsp;&nbsp;Fetching rules...");
	
	var queryParam = "";
	if (role == "admin") {
    queryParam = "&_role=admin";
	}
	$.get("irods.xml?_uri=//com.enginframe.irods/get_irods_rules_local" + queryParam, function(data) {
		var options = data.substring((data.indexOf("##START##") + 9), data.indexOf("##END##"));
		var output = "";
		
		if (options.length != 0) {
			output += "<optgroup id='efRules' label='From EnginFrame'>";
			var tokens = options.split("\n");
			for (var i = 0; i < (tokens.length - 1); i++) {
					output += "<option class='rules-list-item' value='" + tokens[i] + "'>" + tokens[i] + "</option>";
			}		 
			output += "</optgroup>"
		}
		
		$("#rulesList").html(output);
		
		$.get("irods.xml?_uri=//com.enginframe.irods/get_irods_rules_from_collection", function(data) {
			var options = data.substring((data.indexOf("##START##") + 9), data.indexOf("##END##"));
			var output = "";
			
			if (options.length != 0) {
				output += "<optgroup label='From iRODS'>";
				var tokens = options.split("\n");
				for (var i = 0; i < (tokens.length - 1); i++) {
					output += "<option value='___IRODS___" + tokens[i] + "'>" + tokens[i] + "</option>";
				}		 
				output += "</optgroup>"
			}
			
			$("#rulesList").append(output);
			$("#rulesLoading").html("");
		});
	});
}

function appendToRuleText(role) {
  var rulename = $("#rulesList").val();
  if (rulename == undefined) {
    alert("Please select a rule first for content copying.");
    return;
  }
  
  $("#rulesLoading").html("<img src='images/loading.gif'>&nbsp;&nbsp;Fetching rule...");
  
  var queryParam = "";
	if (role == "admin") {
    queryParam = "&_role=admin";
	}
  $.get("irods.xml?_uri=//com.enginframe.irods/cat_irods_rule&_rule_name=" + rulename + queryParam, function(data) {    
    var ruleText = data.substring((data.indexOf("##START##") + 9), data.indexOf("##END##"));
    var oldText = $("#ruleText").val();
    var newText;
    if (oldText.length == 0) {
      newText = ruleText;
    } else {
      newText = oldText + "\n\n" + ruleText;
    }
    $("#ruleText").val(newText);
    $("#rulesLoading").html("");
  });
}

function execSelectedRule(role) {
  $("#ruleOutput").html("<img src='images/loading.gif'>&nbsp;&nbsp;Executing iRODS rule, please wait...");
  
  var queryParam = "";
	if (role == "admin") {
    queryParam = "&_role=admin";
	}
  $.get("irods.xml?_uri=//com.enginframe.irods/exec_irods_selected_rule&_rule_name=" + $("#rulesList").val() + queryParam, function(data) {
    if (data.indexOf("##END##") < 0) {
      $("#ruleOutput").html("The selected rule needs one or more command line parameters: execution aborted.");
    } else {
      var ruleOutput = data.substring((data.indexOf("##START##") + 9), data.indexOf("##END##"));
      $("#ruleOutput").html(ruleOutput);
    }
  });
}

function execRule() {
	$("#ruleOutput").html("<img src='images/loading.gif'>&nbsp;&nbsp;Executing iRODS rule, please wait...");
	
  $.post("irods.xml", {_uri: "//com.enginframe.irods/exec_irods_rule", _rule_content: $("#ruleText").val()}, function(data) {
    $("#ruleInfo").html("Output of rule <b>" + $("#rulesList").val() + "<b>:");
    
    if (data.indexOf("##END##") < 0) {
      $("#ruleOutput").html("The selected rule needs one or more command line parameters: execution aborted.");
    } else {
      var ruleOutput = data.substring((data.indexOf("##START##") + 9), data.indexOf("##END##"));
      $("#ruleOutput").html(ruleOutput);
    }
  });
}

function saveRule(role) {
  var ruleText = $("#ruleText").val();
  if (ruleText.length == 0) {
    alert("Cannot save an empty rule.");
    return;
  }
  
  var ruleName = $("#ruleName").val();
  if (ruleName.length == 0) {
    alert("Please enter a valid rule name.");
    return;
  }
  
  var overwrite = true;
  var newItem = true;
  $(".rules-list-item").each(function () {
    if ($(this).val() == ruleName + ".ir") {
      if (confirm("A rule with file name '" + $(this).val() + "' already exists: overwrite?") == false) {
        overwrite = false;
      } else {
        newItem = false;
      }
      return false;
    }
  });

  if (overwrite) {
  	var queryParam = "";
  	if (role == "admin") {
      queryParam = "&_role=admin";
  	}
    $.post("irods.xml", {_uri: "//com.enginframe.irods/save_irods_rule", _rule_name: ruleName + ".ir", _rule_content: ruleText, _role: role}, function(data) {
      var output = data.substring((data.indexOf("##START##") + 9), data.indexOf("##END##"));
      if (output.length != 0) {
        alert("An error occured saving rule " + $("#ruleName").val() + ".ir:\n\n" + output);
      } else {
        var ruleFilename = $("#ruleName").val() + ".ir";
        alert("Rule " + ruleFilename + " saved correctly.");
        if (newItem) {
          $("#efRules").append("<option value='" + ruleFilename + "' class='rules-list-item'>" + ruleFilename + "</option>");
        }
      }
    });
  }
}
